package logic

import (
	"context"
	"net/http"

	"oil-station-backend/internal/model"
	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"

	"github.com/golang-jwt/jwt/v4"
)

type OrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderLogic {
	return &OrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderLogic) GetOrderList(req *types.OrderListReq, r *http.Request) (*types.OrderListResp, error) {
	// 从JWT中获取用户信息
	token := r.Header.Get("Authorization")
	claims := jwt.MapClaims{}
	_, err := jwt.ParseWithClaims(token[7:], claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(l.svcCtx.Config.Auth.AccessSecret), nil
	})
	if err != nil {
		return nil, err
	}

	userId := int64(claims["userId"].(float64))
	username := claims["username"].(string)

	// 查找用户信息
	user, err := l.svcCtx.UserModel.FindByUsername(username)
	if err != nil {
		return nil, err
	}

	var orders []model.Order
	var total int64

	// 根据用户角色查询订单
	if user.Role == "admin" {
		// 管理员查看所有订单
		orders, total, err = l.svcCtx.OrderModel.FindList(req.Status, req.Page, req.Size)
	} else {
		// 普通用户只能查看自己的订单
		orders, total, err = l.svcCtx.OrderModel.FindList(req.Status, req.Page, req.Size)
		// 过滤出当前用户的订单
		var userOrders []model.Order
		for _, order := range orders {
			if order.UserId == userId {
				userOrders = append(userOrders, order)
			}
		}
		orders = userOrders
		total = int64(len(userOrders))
	}

	if err != nil {
		return nil, err
	}

	var result []types.Order
	for _, order := range orders {
		orderType := types.Order{
			Id:            order.Id,
			OrderNo:       order.OrderNo,
			UserId:        order.UserId,
			UserName:      order.UserName,
			FuelType:      order.FuelType,
			FuelPrice:     order.FuelPrice,
			Volume:        order.Volume,
			PrepaidAmount: order.PrepaidAmount,
			Status:        order.Status,
			CreateTime:    order.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:    order.UpdateTime.Format("2006-01-02 15:04:05"),
		}

		if order.ActualVolume != nil {
			orderType.ActualVolume = *order.ActualVolume
		}
		if order.ActualAmount != nil {
			orderType.ActualAmount = *order.ActualAmount
		}
		if order.CompleteTime != nil {
			orderType.CompleteTime = order.CompleteTime.Format("2006-01-02 15:04:05")
		}

		result = append(result, orderType)
	}

	return &types.OrderListResp{
		List:  result,
		Total: total,
	}, nil
}

func (l *OrderLogic) GetOrderDetail(id int64) (*types.Order, error) {
	order, err := l.svcCtx.OrderModel.FindById(id)
	if err != nil {
		return nil, err
	}

	result := &types.Order{
		Id:            order.Id,
		OrderNo:       order.OrderNo,
		UserId:        order.UserId,
		UserName:      order.UserName,
		FuelType:      order.FuelType,
		FuelPrice:     order.FuelPrice,
		Volume:        order.Volume,
		PrepaidAmount: order.PrepaidAmount,
		Status:        order.Status,
		CreateTime:    order.CreateTime.Format("2006-01-02 15:04:05"),
		UpdateTime:    order.UpdateTime.Format("2006-01-02 15:04:05"),
	}

	if order.ActualVolume != nil {
		result.ActualVolume = *order.ActualVolume
	}
	if order.ActualAmount != nil {
		result.ActualAmount = *order.ActualAmount
	}
	if order.CompleteTime != nil {
		result.CompleteTime = order.CompleteTime.Format("2006-01-02 15:04:05")
	}

	return result, nil
}

func (l *OrderLogic) CompleteOrder(req *types.CompleteOrderReq) (*types.Order, error) {
	// 更新订单状态
	_, err := l.svcCtx.OrderModel.Complete(req.OrderId, req.ActualVolume, req.ActualAmount)
	if err != nil {
		return nil, err
	}

	// 返回更新后的订单信息
	return l.GetOrderDetail(req.OrderId)
}